package com.xingzhe.ucenter.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xingzhe.ucenter.mapper.XcMenuMapper;
import com.xingzhe.ucenter.mapper.XcUserMapper;
import com.xingzhe.ucenter.model.dto.AuthParamsDto;
import com.xingzhe.ucenter.model.dto.XcUserExt;
import com.xingzhe.ucenter.model.po.XcMenu;
import com.xingzhe.ucenter.model.po.XcUser;
import com.xingzhe.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description 自定义UserDetailsService用来对接Spring Security
 * @date 2022/9/28 18:09
 */
@Slf4j
@Component
public class UserServiceImpl  implements UserDetailsService {
    @Resource
    XcUserMapper xcUserMapper;

    @Resource
    ApplicationContext applicationContext;

    @Resource
    XcMenuMapper xcMenuMapper;




    /**
     * @description 查询用户信息组成用户身份信息
     * @param s  AuthParamsDto类型的json数据
     * @return org.springframework.security.core.userdetails.UserDetails
     * @author Mr.M
     * @date 2022/9/28 18:30
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //将传入的Json转为AuthParamsDto对象
        AuthParamsDto authParamsDto=null;
        try {
            authParamsDto=JSON.parseObject(s,AuthParamsDto.class);
        }catch (Exception e){
            throw new RuntimeException("请求认证的参数不符合要求");
        }
        String username= authParamsDto.getUsername();

        //先判断认证的类型是密码模式还是微信扫码模式等
        String authType = authParamsDto.getAuthType();
        //根据认证类型从spring容器取出对应的bean
        String beanName=authType+"_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        //然后统一调用execute方法完成认证
        XcUserExt xcUserExt = authService.execute(authParamsDto);
        //封装xcUserExt用户信息为UserDetails
        UserDetails userPrincipal = getUserPrincipal(xcUserExt);
        return userPrincipal;
    }


    /**
     * @description 查询用户信息
     * @param user  用户id，主键
     * @return com.xingzhe.ucenter.model.po.XcUser 用户信息
     * @author Mr.M
     * @date 2022/9/29 12:19
     */
    public UserDetails getUserPrincipal(XcUserExt user){
        //如果查到用户拿到了正确的密码，最终会封装成一个UserDetails对象给spring security框架返回，有框架进行密码校验
        String password = user.getPassword();
        //用户权限,如果不加报Cannot pass a null GrantedAuthority collection
        String[] authorities= {"test"};
        //根据用户id查询权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(user.getId());
        if (xcMenus.size()>0){
            ArrayList<Object> permission = new ArrayList<>();
            xcMenus.forEach(m->{
                //拿到用户拥有的权限标识符
                permission.add(m.getCode());
            });
            //将permission转为数组
            authorities = permission.toArray(new String[0]);
        }
        user.setPassword(null);
        //将用户信息转为json
        String userJson = JSON.toJSONString(user);
        //创建UserDetails对象,权限信息待实现授权功能时再向UserDetail中加入
        UserDetails userDetails = User.withUsername(userJson).password(password).authorities(authorities).build();
        return userDetails;
    }

}
